import { Button, Drawer, Tree } from 'antd';
import React, { useState, useEffect } from 'react';
import * as api from '@/services/ReportMgr';
import _ from 'lodash';
import qs from 'qs';
// import request from 'umi-request';

function buildTree(list) {
  if (!_.isEmpty(list)) {
    list.forEach(item => {
      const x = item;
      x.title = item.orgName;
      x.key = item.orgId;
      delete x.orgName;
      delete x.orgId;
      if (!_.isEmpty(item.children)) buildTree(item.children);
    });
  }
  return list;
}

export default function ExportModel(props) {
  const [treeData, setTreeData] = useState([]);
  const [visible, setVisible] = useState(false);
  const [checkedKeys, setCheckedKeys] = useState([]);
  const [okLoading, setOkLoading] = useState(false);
  useEffect(() => {
    const func1 = async () => {
      const res = await api.getDivisionUsingGET({});
      if (res && res.code === 1 && !_.isEmpty(res.data)) setTreeData(buildTree(res.data));
    };
    func1();
  }, []);

  // 点击确认导出
  const handleOkBtnClick = async () => {
    setOkLoading(true);
    const params = {
      endDate: props.endTime,
      orgIds: checkedKeys.toString(),
    };
    // 导出校验
    const res = await api.exportCheckUsingGET({ params });
    if (res && res.code === 1 && res.data === 'ok') {
      setVisible(false);
      const sessionToken = localStorage.getItem('sessionToken');
      const exportQueryString = qs.stringify({ ...params, sessionToken });
      window.open(`${process.env.apiUrl}/api/v1/report/removalReportExport?${exportQueryString}`);
    }
    // const res = await api.removalReportExportUsingGET({ params });
    // const url = window.URL.createObjectURL(new Blob([res]))
    // const link = document.createElement('a')
    // link.style.display = 'none'
    // link.href = url
    // link.setAttribute('download', 'excel.xlsx')
    // document.body.appendChild(link)
    // link.click()
    // document.body.removeChild(link)

    // const fileName = '去化率分析表-截止202010-2020102721.xlsx'
    // const link = document.createElement('a')
    // link.download = fileName
    // link.style.display = 'none'
    // link.href = URL.createObjectURL(new Blob([res]))
    // document.body.appendChild(link)
    // link.click()
    // URL.revokeObjectURL(link.href)
    // document.body.removeChild(link)
    // if (res) {
    //   debugger
    //   const link = document.createElement('a');
    //   link.style.display = 'none';
    //   link.href = window.URL.createObjectURL(res.blob);
    //   link.download = res.fileName.replace('attachment;filename=', '');
    //   link.click(); // 模拟点击a标签
    //   window.URL.revokeObjectURL(link.href);
    // }
    setTimeout(() => setOkLoading(false), 500);
  };

  return (
    <>
      <Button className="yellow-button" onClick={() => setVisible(true)} disabled={props.disabled}>
        导出报表
      </Button>
      <Drawer
        title="导出报表"
        placement="right"
        closable={false}
        onClose={() => setVisible(false)}
        visible={visible}
      >
        <>
          <Tree
            defaultExpandAll
            treeData={treeData}
            checkable
            onCheck={keys => setCheckedKeys(_.filter(keys, x => x !== '00000001'))}
          />
          <div
            style={{
              position: 'absolute',
              left: 0,
              bottom: 0,
              width: '100%',
              borderTop: '1px solid #e9e9e9',
              padding: '10px 16px',
              background: '#fff',
              textAlign: 'center',
            }}
          >
            <Button onClick={() => setVisible(false)} style={{ marginRight: 8 }}>
              关闭
            </Button>
            <Button
              onClick={handleOkBtnClick}
              type="primary"
              disabled={_.isEmpty(checkedKeys)}
              loading={okLoading}
            >
              确认
            </Button>
          </div>
        </>
      </Drawer>
    </>
  );
}
